package com.qfedu.knowledge.config;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.knowledge.entity.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName TokenInterceptor
 * @Author ykx
 * @Date 2024/4/27 11:04
 * @Version 1.0
 */
@Configuration
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("uri = " + uri);
        if (CommonConstant.WHITE_LIST.contains(uri) || uri.contains("swagger") || uri.contains("actuator")) {
            return true;
        }

        // 处理token
        String token = request.getHeader(jwtConfig.getHeader());
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(jwtConfig.getHeader());
        }

        if (StringUtils.isEmpty(token)) {
            // 返回401，token不能为空
            sendError(response, "token不能为空");
            return false;
        }

        try {
            jwtConfig.getTokenClaim(token);
            System.out.println(jwtConfig.getSubject(token));
        } catch (Exception e) {
            sendError(response, "token无效");
            return false;
        }
        return true;

    }

    private void sendError(HttpServletResponse response, String msg) throws IOException {
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(msg);
    }

}
